{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a3b3eac1",
   "metadata": {},
   "outputs": [
    {
     "ename": "ModuleNotFoundError",
     "evalue": "No module named 'pydotplus'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mModuleNotFoundError\u001b[0m                       Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_15612/795806994.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mnumpy\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0msklearn\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mtree\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[1;32mimport\u001b[0m \u001b[0mpydotplus\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      5\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      6\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0mcreateTree\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mtrainingData\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'pydotplus'"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "from sklearn import tree\n",
    "import pydotplus\n",
    "\n",
    "def createTree(trainingData):\n",
    "    \"\"\"\n",
    "    创建决策树模型\n",
    "    \n",
    "    参数:\n",
    "        trainingData: 包含特征和标签的DataFrame\n",
    "    返回:\n",
    "        训练好的决策树模型\n",
    "    \"\"\"\n",
    "    data = trainingData.iloc[:, :-1]  # 特征矩阵\n",
    "    labels = trainingData.iloc[:, -1]  # 标签\n",
    "    trainedTree = tree.DecisionTreeClassifier(criterion=\"entropy\")  # 使用信息熵划分\n",
    "    trainedTree.fit(data, labels)\n",
    "    return trainedTree\n",
    "\n",
    "def showtree2pdf(trainedTree, filename):\n",
    "    \"\"\"\n",
    "    将决策树可视化并保存为PDF\n",
    "    \n",
    "    参数:\n",
    "        trainedTree: 训练好的决策树模型\n",
    "        filename: 输出的PDF文件名\n",
    "    \"\"\"\n",
    "    dot_data = tree.export_graphviz(trainedTree, out_file=None)  # 导出为Graphviz格式\n",
    "    graph = pydotplus.graph_from_dot_data(dot_data)\n",
    "    graph.write_pdf(filename)  # 保存为PDF\n",
    "\n",
    "def data2vector(data):\n",
    "    \"\"\"\n",
    "    将类别型数据转换为数值型\n",
    "    \n",
    "    参数:\n",
    "        data: 包含类别特征的DataFrame\n",
    "    返回:\n",
    "        转换后的DataFrame\n",
    "    \"\"\"\n",
    "    names = data.columns[:-1]\n",
    "    for i in names:\n",
    "        col = pd.Categorical(data[i])\n",
    "        data[i] = col.codes  # 将类别标签转为数值编码\n",
    "    return data\n",
    "\n",
    "def main():\n",
    "    # 读取数据集\n",
    "    try:\n",
    "        data = pd.read_table(\"tennis.txt\", header=None, sep='\\t')\n",
    "        print(\"数据集加载成功！\")\n",
    "        print(\"\\n数据集预览：\")\n",
    "        print(data.head())\n",
    "        \n",
    "        # 向量化处理\n",
    "        trainingvec = data2vector(data)\n",
    "        print(\"\\n向量化后的数据：\")\n",
    "        print(trainingvec.head())\n",
    "        \n",
    "        # 生成决策树\n",
    "        decisionTree = createTree(trainingvec)\n",
    "        print(\"\\n决策树模型训练完成！\")\n",
    "        \n",
    "        # 保存决策树可视化结果\n",
    "        showtree2pdf(decisionTree, \"tennis.pdf\")\n",
    "        print(\"\\n决策树已保存为 tennis.pdf\")\n",
    "        \n",
    "    except FileNotFoundError:\n",
    "        print(\"错误：找不到数据集文件 'tennis.txt'\")\n",
    "    except Exception as e:\n",
    "        print(f\"发生错误：{str(e)}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5b1e1094",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
